package com.zhou.dynamo.db.repository;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author Mr.zhou
 */
public class AbstractRepository {
    protected static Logger log = LoggerFactory.getLogger("DYNAMODB_REPOSITORY");
    // 全局连接对象
    protected static DynamoDB _dynamo;
    private static String endpoint = "http://localhost:8000/";
    private static String ENV = "env";
    private static boolean _initialized = false;
    private static String AWSID = "";
    private static String AWSKEY = "";
    private static final String PROD="prod";

    public AbstractRepository() {
        super();
        ensureInitialized();
    }

    /**
     * 确保该对象已初始化
     */
    private static void ensureInitialized() {
        if (_initialized) {
            return;
        }
        log.info("Initializing dynamoDB repository...");

        // 若权限配置文件名为空，则不需要权限配置文件（一般情况为部署到EC2而且EC2已经绑定了dynamoDB的访问权限）
        AmazonDynamoDBClient client = null;
        if (PROD.equals(ENV)) {
            client = new AmazonDynamoDBClient();
        } else {
            client = new AmazonDynamoDBClient(awsTestCredentials());
        }
        client.setEndpoint(endpoint);
        // client.setRegion(Region.getRegion(Regions.US_WEST_2));
        _dynamo = new DynamoDB(client);
        _initialized = true;
    }

    /**
     * 读取dynamoDB账号信息
     */
    protected static AWSCredentials awsTestCredentials() {
        AWSCredentials credentials = null;
        credentials = new AWSCredentials() {
            @Override
            public String getAWSSecretKey() {
                return AWSID;
            }
            @Override
            public String getAWSAccessKeyId() {
                return AWSKEY;
            }
        };
        return credentials;
    }

    public static DynamoDB getDynamoDB() {
        return _dynamo;
    }
}
